package com.xiaomaoguai.redis.sub2;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

/**
 * @ FileName: AbstractMessageDelegate.java
 * @ Author: WeiHui-Z
 * @ Date: 2017/4/21 17:26
 * @ Version: v1.0.0
 */
public abstract class AbstractMessageDelegate implements MessageDelegate {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void handleMessage(Map<String, String> message, String channel) {
        logger.info("订阅到:[{}]的消息", channel);
        logger.info("消息内容:[{}]", message);

        String userId = message.get("userId");
        String extendField = message.get("extendField");

        //1、检验参数--推送类型
        if (StringUtils.isAnyBlank(channel, userId, extendField)) {
            return;
        }

        try {
            //2、设置接受者
            List<String> receivers = handleReceivers(userId);

            //3、设置推送数据实体
            Object data = handlePushData(extendField);

            //4、包装推送model
            WebSocketMessageModel messageModel = new WebSocketMessageModel();
            messageModel.setReceivers(receivers);
            messageModel.setData(data);
            messageModel.setType(Integer.parseInt(PushMsgEnum.getTypeByName(channel)));

            //5、推送数据
            System.out.println(messageModel);

        } catch (Exception e) {
            logger.error("查询待推送数据出错,当前参数[type:{},extendField:{},userId:{}]", channel, extendField, userId, e);
        }
    }

    protected abstract List<String> handleReceivers(String userId) throws Exception;

    protected abstract Object handlePushData(String extendField) throws Exception;
}
